//
//  LoginVC.m
//  NJUSTHelper
//
//  Created by 郑越辉 on 2017/9/15.
//  Copyright © 2017年 njust. All rights reserved.
//

#import "LoginVC.h"
#import "Define.h"
#import "UserDBService.h"
#import "DefineURL.h"
#import <TFHpple.h>
@interface LoginVC ()
@property (weak, nonatomic) IBOutlet UIView *topview;
@property (weak, nonatomic) IBOutlet UITextField *loginNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *libraryPwdTextField;

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"账号";
    self.view.backgroundColor = [UIColor colorWithRed:27.0/255.0 green:164.0/255.0 blue:218.0/255.0 alpha:0.8];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"login_right_finish"] style:UIBarButtonItemStylePlain target:self action:@selector(inputFinishAction)];
    [self.navigationItem setRightBarButtonItem:rightBarItem];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"login_left_cancel"] style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    [self.navigationItem setLeftBarButtonItem:leftBarItem];
    ///图书馆暂未开放,图书馆密码不可编辑
    self.libraryPwdTextField.enabled = NO;
    
    if([AccountInfo.userId length] > 0){
        self.loginNameTextField.text = AccountInfo.userId;
        self.passwordTextField.text = AccountInfo.password;
    }
    
    self.topview.layer.borderWidth = 0.5;
    self.topview.layer.borderColor = Default_BorderColor.CGColor;
    self.topview.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
    self.topview.layer.shadowOffset = CGSizeMake(1,2);//shadowOffset阴影偏移,x向右偏移，y向下偏移
    self.topview.layer.shadowOpacity = 0.10;//阴影透明度，默认0
    self.topview.layer.shadowRadius = 2;//阴影半径，默认3

    
    
}

-(void)inputFinishAction{
    if(![self checkInput]){
        return;
    }
    
    [SVProgressHUD show];
    AccountInfo.userId = self.loginNameTextField.text;
    if(![self.passwordTextField.text isEqualToString:AccountInfo.password]) {
        AccountInfo.password = [NSString MD5ForUpper32Bate:self.passwordTextField.text];
    }
    AccountInfo.isLogin = YES;
    ///清除上次登录信息
    [ASIFormDataRequest clearSession];
    ASIFormDataRequest *req  =  [HtmlAnalysisHelper requestForLogin];
    NSString *loginStr = [req responseString];
    NSString *patternStr = @"用户名或密码错误";
    if([[loginStr firstMatchWithPattern:patternStr] length] > 0) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showInfoWithStatus:@"账号或密码错误"];
        return;
    }
    if([[loginStr firstMatchWithPattern:@"打开新窗口"] length] > 0) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showInfoWithStatus:@"要登录不同的账号请先退出"];
        return;
    }
    ///获取用户名
    TFHpple *hpple = [[TFHpple alloc]initWithHTMLData:[req responseData]];
    NSArray * dataArray = [hpple searchWithXPathQuery:@"//div"] ;
    
    for (TFHppleElement * element in dataArray) {
        if ([[element objectForKey:@"class"]isEqualToString:NAME_CLASS]) {
            NSString *name = element.content;
            name = [name stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"(%@)", AccountInfo.userId] withString:@""];
            AccountInfo.userName = name;
            
        }
        
    }
    UserModel *user = [[UserModel alloc]init];
    user.userId = AccountInfo.userId;
    user.userName = AccountInfo.userName;
    user.userCode = AccountInfo.userCode;
    user.libraryPwd = AccountInfo.libraryPwd;
    user.password = AccountInfo.password;
    user.isLogin = AccountInfo.isLogin;
    if(![UserDBService checkUserIsExistWithID:AccountInfo.userId]){
        ///初次登录,insert
        NSLog(@"初次登录");
        [UserDBService logoutAllUser];
        [UserDBService addUser:user];
    }else {
        ///有登录过,update
        NSLog(@"再次登录");
        [UserDBService logoutAllUser];
        [UserDBService updateUser:user];
    }
    
    [HtmlAnalysisHelper analysiScheduleAndSave];
    
    [SVProgressHUD dismiss];
    [SVProgressHUD showSuccessWithStatus:@"登录成功"];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//输入校验
-(BOOL)checkInput{
    if([self.loginNameTextField.text length] == 0) {
        [SVProgressHUD showInfoWithStatus:@"登录账号不能为空!"];
        return NO;
    }
    if([self.passwordTextField.text length] == 0 ){
        [SVProgressHUD showInfoWithStatus:@"教务处密码不能为空!"];
        return NO;
    }
    ///图书馆功能尚未开放
//    if([self.libraryPwdTextField.text length] == 0) {
//        [SVProgressHUD showInfoWithStatus:@"图书馆密码不能为空!"];
//        return NO;
//    }
    return YES;
}

-(void)cancelAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}


@end
